package com.huang.controller;

import com.aliyuncs.utils.StringUtils;
import com.huang.service.SendSms;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin//跨域支持
public class SmsApiController {
    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/send/{phone}")
    public String ccde(@PathVariable("phone") String phone){
        //模拟真实调用
        String code= (String) redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return phone+":"+"已存在，还未过期";
        }

        //生成验证码并存储到redis中
        code= UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param=new HashMap<>();
        param.put("code",code);

        boolean isSend=sendSms.send(phone,"SMS_189521253",param);

        if (isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return phone+":"+code+"发送成功";
        }else {
            return "发送失败";
        }
    }
}
